package com.heaton.videocar

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.annotation.MainThread
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.createViewModelLazy
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
import androidx.lifecycle.ViewModelProvider
import com.heaton.baselib.app.event.LiveDataBus
import com.heaton.baselib.base.recycleview.RecyclerAdapter
import com.heaton.baselib.callback.CallBackUI
import com.heaton.baselib.utils.*


/**
 * description $desc$
 * created by jerry on 2019/5/4.
 */

@MainThread
inline fun <reified VM : ViewModel> Fragment.appViewModels(
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
) = createViewModelLazy(VM::class, { App.instace.getViewModelStore() }, factoryProducer)

//全局共享viewmodel(多activity、fragment间共享数据)
@MainThread
inline fun <reified VM : ViewModel> ComponentActivity.appViewModels(
    noinline factoryProducer: (() -> ViewModelProvider.Factory)? = null
):Lazy<VM> {
    val factoryPromise = factoryProducer ?: {
        defaultViewModelProviderFactory
    }
    return ViewModelLazy(VM::class, { App.instace.getViewModelStore() }, factoryPromise)
}

fun Context.toast(message: String?, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, message, duration).show()
}

fun isRepeatClick(duration: Long = 500L): Boolean{
    return ViewUtils.filter(duration)
}

fun setOnClicks(listener: View.OnClickListener, vararg views: View){
    for (it in views){
        it.setOnClickListener(listener)
    }
}

fun View.setOnClickFilterListener(l: () -> Unit){
    setOnClickListener {
        if (!isRepeatClick()){
            l.invoke()
        }
    }
}

fun SeekBar.setOnSeekBarStopChangeListener(l: (seekBar: SeekBar)-> Unit){
    setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
        override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {}
        override fun onStartTrackingTouch(seekBar: SeekBar) {}
        override fun onStopTrackingTouch(seekBar: SeekBar) {
            l.invoke(seekBar)
        }
    })
}

fun <T>RecyclerAdapter<T>.setOnItemClickFilterListener(l: (parent: ViewGroup,view: View,t: T,position: Int) -> Unit) {
    setOnItemClickListener { parent, view, t, position ->
        if (!isRepeatClick()){
            l.invoke(parent, view, t, position)
        }
    }
}

fun View.show(){
    visibility = View.VISIBLE
}

fun View.hide(){
    visibility = View.GONE
}

fun View.invisible(){
    visibility = View.INVISIBLE
}

fun <T> post(eventKey: String, value: T){
    LiveDataBus.get().with(eventKey).postValue(value)
}

inline fun <reified T>subscribe(eventKey: String): LiveDataBus.Observable<T> {
    return LiveDataBus.get().with(eventKey, T::class.java)
}

fun Fragment.showDialog(title:String="", message: String, positive:()-> Unit){
    DialogUtils.showCommonDialog(activity,title, message, object : DialogUtils.DialogCall(){
        override fun onPositive(dialog: DialogInterface?) {
            positive.invoke()
        }
    })
}

fun Activity.showDialog(title:String="", message: String, positive:()-> Unit){
    DialogUtils.showCommonDialog(this,title, message, object : DialogUtils.DialogCall(){
        override fun onPositive(dialog: DialogInterface?) {
            positive.invoke()
        }
    })
}

var loadingDialog: AlertDialog?=null

@JvmOverloads
fun Activity.showLoadingDialog(show: Boolean = true, message: String="加载中..."){
    if (show){
        if (loadingDialog == null){
            loadingDialog = AlertDialog.Builder(this)
                .setView(R.layout.dialog_loading)
                .setCancelable(false)
                .show()
        }
        val content = loadingDialog?.findViewById<TextView>(R.id.tipTextView)
        content?.text = message
        loadingDialog?.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
    }else{
        loadingDialog?.dismiss()
        loadingDialog = null
    }
}

@JvmOverloads
fun Fragment.showLoadingDialog(show: Boolean = true, message: String="加载中..."){
    activity?.showLoadingDialog(show, message)
}

fun async(callback:()-> Unit){
    ThreadUtils.async(callback)
}

fun asyncDelay(delay: Long, callback:()-> Unit){
    ThreadUtils.asyncDelay(delay, callback)
}

fun <T> asyncCallback(callback: CallBackUI<T>){
    ThreadUtils.asyncCallback(callback)
}

fun ui(callback:()-> Unit){
    ThreadUtils.ui(callback)
}

fun getColor(resId: Int): Int{
    return ContextUtils.getColor(resId)
}

fun setTimeout(id: Int=0, duration: Long, runnable:()->Unit){
    ThreadUtils.ui{
        HandlerUtils.setTimeout(id, duration, runnable)
    }
}

fun removeTimeout(id: Int=0){
    HandlerUtils.removeTimeout(id)
}

//file kt
fun String.deleteFile(){
    FileUtils.deleteFile(this)
}

//判断当前是否是自己的设备
fun isSelfDevice(address: String): Boolean {
    val lastAddress = SPUtils.get(App.context, Constants.SP_CONNECTED_ADDRESS, "")
    if (!TextUtils.equals(address, lastAddress)){
        return false
    }
    return true
}


